/**
 * 聊天数据模拟模块
 * 使用 Mock.js 生成聊天会话和消息数据
 * @author LYC
 * @date 2025-09-16
 */

import Mock from 'mockjs'
import type { ChatSession, Contact, Message } from '@/store/chat/type'
import type { UserInfo } from '@/store/user/type'

const Random = Mock.Random

// 当前用户信息
export const currentUser: UserInfo = {
  id: 'current-user',
  username: 'lyc_admin',
  nickname: '刘奕川',
  avatar: './src/assets/imgs/LYC.png',
  status: 'online',
  email: 'lyc@example.com'
}

// 创建随机联系人数据
export const generateContacts = (count: number = 10): Contact[] => {
  const contacts: Contact[] = []

  // 添加固定联系人 - XL
  contacts.push({
    id: 'xl-user',
    username: 'xl_user',
    nickname: 'XL',
    avatar: './src/assets/imgs/XL.png',
    status: 'online',
    lastSeen: new Date(),
    isBlocked: false,
    type: 'friend'
  })

  // 添加随机联系人
  for (let i = 1; i < count; i++) {
    const firstName = Random.cfirst()
    const lastName = Random.clast()
    const name = lastName + firstName
    const pinyin = Random.word(3, 6).toLowerCase()
    const lastSeenTime = new Date(Date.now() - Random.integer(1, 7) * 86400000)

    contacts.push({
      id: `user-${i}`,
      username: `${pinyin}${Random.integer(100, 999)}`,
      nickname: name,
      avatar: Random.image('100x100', Random.color(), '#FFF', 'png', name.substring(0, 1)),
      status: Random.pick(['online', 'offline', 'busy', 'away']),
      lastSeen: lastSeenTime,
      isBlocked: Random.boolean(0.05), // 5%概率被拉黑
      lastMessage: Random.ctitle(5, 15),
      type: 'friend'
    })
  }

  return contacts
}

// 聊天消息类型随机内容生成器
const generateMessageContent = (type: 'text' | 'image' | 'file' | 'voice' | 'video'): string => {
  switch (type) {
    case 'text':
      return Random.csentence(5, 50)
    case 'image':
      return '[图片]'
    case 'file':
      return `[文件] ${Random.word(3, 8)}.${Random.pick(['pdf', 'doc', 'xlsx', 'zip'])}`
    case 'voice':
      return `[语音] ${Random.integer(1, 2)}:${Random.integer(10, 59)}`
    case 'video':
      return '[视频]'
    default:
      return Random.csentence(5, 30)
  }
}

// 自定义权重随机选择函数，因为Mock.js没有内置weights函数
const weightedRandom = <T>(items: T[], weights: number[]): T => {
  // 确保权重和项目数组长度相同
  if (items.length !== weights.length) {
    throw new Error('Items and weights arrays must be of the same length')
  }

  // 计算权重总和
  const totalWeight = weights.reduce((sum, weight) => sum + weight, 0)

  // 生成一个0到权重总和的随机数
  const randomValue = Math.random() * totalWeight

  // 根据权重选择项目
  let weightSum = 0
  for (let i = 0; i < items.length; i++) {
    weightSum += weights[i]
    if (randomValue <= weightSum) {
      return items[i]
    }
  }

  // 默认返回最后一项（理论上不应该到达这里）
  return items[items.length - 1]
}

// 为联系人创建模拟消息历史
export const generateMessageHistory = (contactId: string, count: number = 20): Message[] => {
  const messages: Message[] = []
  const currentTime = Date.now()
  const twoWeeksInMs = 14 * 24 * 60 * 60 * 1000
  const startTime = currentTime - twoWeeksInMs

  for (let i = 0; i < count; i++) {
    const timestamp = new Date(startTime + ((currentTime - startTime) * i) / count)
    const isFromMe = Random.boolean()
    const messageType = weightedRandom(
      ['text', 'image', 'file', 'voice', 'video'],
      [80, 10, 5, 3, 2]
    )

    messages.push({
      id: `msg-${contactId}-${i}`,
      senderId: isFromMe ? currentUser.id : contactId,
      receiverId: isFromMe ? contactId : currentUser.id,
      content: generateMessageContent(messageType as 'text' | 'image' | 'file' | 'voice' | 'video'),
      type: messageType as 'text' | 'image' | 'file' | 'voice' | 'video',
      timestamp,
      status: 'read' as const
    })
  }

  // 确保最后一条消息是最近的
  messages.sort((a, b) => a.timestamp.getTime() - b.timestamp.getTime())

  return messages
}

// 生成会话列表数据
export const generateChatSessions = (contacts: Contact[]): ChatSession[] => {
  const sessions: ChatSession[] = []

  contacts.forEach((contact) => {
    // 为每个联系人生成10-30条历史消息
    const messageCount = Random.integer(10, 30)
    const messages = generateMessageHistory(contact.id, messageCount)
    const lastMessage = messages[messages.length - 1]

    sessions.push({
      id: contact.id,
      type: 'private',
      name: contact.nickname,
      avatar: contact.avatar,
      lastMessage,
      unreadCount: Random.integer(0, 8),
      lastActiveTime: lastMessage.timestamp,
      participants: [currentUser.id, contact.id]
    })
  })

  // 按最后活跃时间排序
  sessions.sort((a, b) => b.lastActiveTime.getTime() - a.lastActiveTime.getTime())

  return sessions
}

// 获取特定聊天的消息记录
export const getChatMessages = (contactId: string): Message[] => {
  return generateMessageHistory(contactId, Random.integer(20, 50))
}

// 定义聊天数据的返回类型
interface ChatData {
  currentUser: UserInfo
  contacts: Contact[]
  sessions: ChatSession[]
  messageHistories: {
    [key: string]: Message[]
  }
}

// 生成完整的聊天数据
export const generateChatData = (): ChatData => {
  const contacts = generateContacts(15) // 创建15个联系人
  const sessions = generateChatSessions(contacts)

  // 特别处理固定联系人XL的消息
  const xlMessages = [
    {
      id: 'xl-msg-1',
      senderId: 'xl-user',
      receiverId: currentUser.id,
      content: '你好，最近工作怎么样？',
      type: 'text' as const,
      timestamp: new Date(Date.now() - 3600000),
      status: 'read' as const
    },
    {
      id: 'xl-msg-2',
      senderId: currentUser.id,
      receiverId: 'xl-user',
      content: '挺忙的，正在开发XLChat应用',
      type: 'text' as const,
      timestamp: new Date(Date.now() - 3540000),
      status: 'read' as const
    },
    {
      id: 'xl-msg-3',
      senderId: 'xl-user',
      receiverId: currentUser.id,
      content: '听起来很有意思！项目进展如何了？',
      type: 'text' as const,
      timestamp: new Date(Date.now() - 3480000),
      status: 'read' as const
    },
    {
      id: 'xl-msg-4',
      senderId: currentUser.id,
      receiverId: 'xl-user',
      content: '已经完成了基础架构和UI设计，现在正在实现聊天功能',
      type: 'text' as const,
      timestamp: new Date(Date.now() - 3420000),
      status: 'read' as const
    },
    {
      id: 'xl-msg-5',
      senderId: 'xl-user',
      receiverId: currentUser.id,
      content: '加油！期待看到最终成果',
      type: 'text' as const,
      timestamp: new Date(Date.now() - 3360000),
      status: 'read' as const
    }
  ]

  // 更新XL的会话信息
  const xlSession = sessions.find((session) => session.id === 'xl-user')
  if (xlSession) {
    xlSession.lastMessage = xlMessages[xlMessages.length - 1]
    xlSession.lastActiveTime = xlMessages[xlMessages.length - 1].timestamp
    xlSession.unreadCount = 2
  }

  return {
    currentUser,
    contacts,
    sessions,
    messageHistories: {
      'xl-user': xlMessages
      // 其他联系人的消息可以按需生成
    }
  }
}

export default {
  currentUser,
  generateContacts,
  generateMessageHistory,
  generateChatSessions,
  getChatMessages,
  generateChatData
}
